﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Xml;
using System.Runtime.InteropServices;

using System.Windows.Forms;

using Service = Kiiro.MSProjectPlugin.PluginHelpers.Service;

namespace Kiiro.MSProjectPlugin
{
    public class SharePointProvider
    {
        internal static void IsUserValid(Service service, PluginHelpers.PromptForm prompt)
        {
            KiiroService.Service midoriService = new KiiroService.Service();

            midoriService.Url = PluginHelpers.GetServiceUrl(service.Path);

            // -- Attempt AD login with Default Credentials --
            try
            {
                midoriService.Credentials = CredentialCache.DefaultCredentials;
                service.UserId = midoriService.IsProjectManager(System.Security.Principal.WindowsIdentity.GetCurrent().Name, service.Path);

                // Set Credentials if successful
                if (service.UserId != 0)
                {
                    service.Credentials = midoriService.Credentials;
                    service.Cookie = null;
                }
            }
            catch (Exception)
            {
                service.UserId = 0;
            }

            // -- Attempt Login with Prompt --
            if (service.UserId == 0)
            {
                int attempts = 0;                                
                while (attempts < 3 && service.UserId == 0)
                {
                    if (attempts > 0) prompt.Retry(); else prompt.Login();
                    if (PluginHelpers.dialogResult == DialogResult.OK)
                    {
                        PluginHelpers.dialogResult = DialogResult.None;
                        attempts++;

                        string domain = string.Empty;
                        string name = string.Empty;
                        string login = prompt.Controls["txtUserName"].Text;
                        string password = prompt.Controls["txtPassword"].Text;

                        // Parse login for domain
                        if (!string.IsNullOrEmpty(login))
                        {
                            string[] split = login.Split("\\".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                            if (split.Length > 1)
                            {
                                domain = split[0];
                                name = split[1];
                            }                           
                        }

                        // -- Attempt AD login with prompted information --
                        try
                        {
                            midoriService.Credentials = !string.IsNullOrEmpty(domain) ? new NetworkCredential(name, password, domain) : new NetworkCredential(login, password);
                            service.UserId = midoriService.IsProjectManager(login, service.Path);

                            // Set Credentials if successful
                            if (service.UserId != 0)
                            {
                                service.Credentials = midoriService.Credentials;
                                service.Cookie = null;
                            }
                        }
                        catch (Exception)
                        {
                            service.UserId = 0;
                        }

                        if (service.UserId == 0)
                        {
                            // -- Attempt Forms Login --
                            try
                            {
                                WebServiceAuth.Authentication auth = new WebServiceAuth.Authentication();
                                auth.Credentials = CredentialCache.DefaultCredentials;
                                auth.Url = PluginHelpers.GetAuthenticationUrl(service.Path);
                                auth.CookieContainer = new CookieContainer();
                                WebServiceAuth.LoginResult result = auth.Login(login, password);
                                if (result.ErrorCode == WebServiceAuth.LoginErrorCode.NoError)
                                {
                                    CookieCollection cookies = auth.CookieContainer.GetCookies(new Uri(auth.Url));
                                    Cookie authCookie = cookies[result.CookieName];

                                    midoriService.CookieContainer = new CookieContainer();
                                    midoriService.CookieContainer.Add(authCookie);
                                    service.UserId = midoriService.IsProjectManager(login, service.Path);
                                    // Set Cookie if successful
                                    if (service.UserId != 0)
                                    {
                                        service.Cookie = authCookie;
                                        service.Credentials = null;
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                service.UserId = 0;
                            }
                        }
                    }
                    else
                    {
                        attempts = 3;
                        PluginHelpers.dialogResult = DialogResult.None;
                        prompt.lblFailure.Text = "Changes made will not be reflected in Kiiro. To preserve the Project file a \"Save As...\" is recommended.";
                    }
                }                
            }
            prompt.Waiting();
        }

        internal static void DownloadMidoriToProject(MSProject.Project project, Service service)
        {
            KiiroService.Service midoriService = new KiiroService.Service();
            midoriService.Url = PluginHelpers.GetServiceUrl(service.Path);

            // Set Authentication Method
            try
            {
                if (service.Credentials != null)
                    midoriService.Credentials = service.Credentials;
                else if (service.Cookie != null)
                {
                    midoriService.CookieContainer = new CookieContainer();
                    midoriService.CookieContainer.Add(service.Cookie);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            try
            {
                XmlDocument xmlMidori = new XmlDocument();
                //Get from Midori
                xmlMidori.InnerXml = midoriService.MidoriToProject(service.Path, service.Name, service.UserId).ToString();

                if (xmlMidori.HasChildNodes)
                {
                    // Resync to Midori
                    PluginHelpers.UpdateProject(project, xmlMidori);

                    int oldCount = project.Tasks.Count;
                    PluginHelpers.UpdateTasks(project, xmlMidori);
                    int newCount = project.Tasks.Count;

                    for (int i = oldCount + 1; i <= newCount; i++)
                    { 
                        while(project.Tasks[i].OutlineParent.Name != project.Tasks[1].OutlineParent.Name)
                        {
                            project.Tasks[i].OutlineOutdent();
                        }
                    }                    
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        internal static void SyncProjectToMidori(MSProject.Project project, Service service)
        {
            KiiroService.Service midoriService = new KiiroService.Service();
            midoriService.Url = PluginHelpers.GetServiceUrl(service.Path);

            // Set Authentication Method
            try
            {
                if (service.Credentials != null)
                    midoriService.Credentials = service.Credentials;
                else if (service.Cookie != null)
                {
                    midoriService.CookieContainer = new CookieContainer();
                    midoriService.CookieContainer.Add(service.Cookie);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
           
            try
            {
                XmlDocument xmlTasks = new XmlDocument();
                xmlTasks.LoadXml("<Tasks></Tasks>");
                xmlTasks = PluginHelpers.FindChanges(service.OldTasks, project);
                
                XmlDocument xmlProject = PluginHelpers.ProjectToXml(project);

                midoriService.ProjectToMidori(xmlProject, xmlTasks, service.Path, service.Name, service.UserId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        internal static void IsDirty(Service service, out bool firstSync, out bool isDirty)
        {
            firstSync = true;
            isDirty = false;

            KiiroService.Service midoriService = new KiiroService.Service();
            midoriService.Url = PluginHelpers.GetServiceUrl(service.Path);

            // Set Authentication Method
            try
            {
                if (service.Credentials != null)
                    midoriService.Credentials = service.Credentials;
                else if (service.Cookie != null)
                {
                    midoriService.CookieContainer = new CookieContainer();
                    midoriService.CookieContainer.Add(service.Cookie);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            try
            {
                isDirty = midoriService.IsDirty(service.Path, service.UserId, out firstSync);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        internal static bool VersionCheck(Service service, Version version)
        {
            bool versionOk = false; 

            KiiroService.Service midoriService = new KiiroService.Service();
            midoriService.Url = PluginHelpers.GetServiceUrl(service.Path);

            // Set Authentication Method
            try
            {
                if (service.Credentials != null)
                    midoriService.Credentials = service.Credentials;
                else if (service.Cookie != null)
                {
                    midoriService.CookieContainer = new CookieContainer();
                    midoriService.CookieContainer.Add(service.Cookie);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            try
            {
                versionOk = midoriService.VersionCheck(service.Path, service.UserId, version.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return versionOk;
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.MSProjectPlugin/SharePointProvider.cs $
 * 
 * 10    10/02/09 10:46a Stefanf
 * 
 * 9     8/31/09 3:36p Stefanf
 * 
 * 8     17/08/09 10:45a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/